package com.coder520.mamabike.security;

import com.coder520.mamabike.utils.PropertiesUtil;

import javax.crypto.Cipher;
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * Created by ASUS on 2017/8/11.
 */
public class RSAUtil {

    private static final String PUBLIC_KEY_NAME = "public_key";

    private static final String PRIVATE_KEY_NAME = "private_key";



    /**
     * * 解密 *
     *
     */
    public static byte[] decrypt(byte[] data) throws Exception {
        byte[] key = Base64Utils.decode(PropertiesUtil.getProperty(PRIVATE_KEY_NAME));
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE,privateKey);
        return cipher.doFinal(data);
    }

    /**
     * 加密
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data) throws Exception {
        byte[] keyBys = Base64Utils.decode(PropertiesUtil.getProperty(PUBLIC_KEY_NAME));

        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBys);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE,publicKey);
        return cipher.doFinal(data);
    }

}